import { LogCategory } from './logCategory';

export interface LogGroupConfig {
  categories: Record<string, boolean>;
  prefix?: string;
  active?: boolean;
}

export class LogCategoryGroup {
  private groups: Record<string, LogGroupConfig> = {};
  private categoryToGroups: Record<string, string[]> = {}; // 分类 -> 所属分组映射

  registerGroup(
    logCategory: LogCategory,
    groupName: string,
    categories: string[],
    prefix?: string,
    active: boolean = false
  ) {
    const validCategories = Object.keys(logCategory.getAllRegisteredCategories());
    const invalid = categories.filter((cat) => !validCategories.includes(cat));
    if (invalid.length > 0) {
      throw new Error(
        `LogCategoryGroup 注册失败，以下分类未在 LogCategory 中注册: ${invalid.join(', ')}`
      );
    }

    const catMap: Record<string, boolean> = {};
    categories.forEach((cat) => {
      catMap[cat] = true;
      if (!this.categoryToGroups[cat]) this.categoryToGroups[cat] = [];
      this.categoryToGroups[cat].push(groupName);
    });

    this.groups[groupName] = {
      categories: catMap,
      prefix,
      active
    };
  }

  registerGroups(
    logCategory: LogCategory,
    groups: Record<string, { categories: string[]; prefix?: string; active?: boolean }>
  ) {
    Object.entries(groups).forEach(([groupName, cfg]) => {
      this.registerGroup(logCategory, groupName, cfg.categories, cfg.prefix, cfg.active ?? false);
    });
  }

  getGroupsForCategory(category: string): string[] {
    return this.categoryToGroups[category] || [];
  }

  getGroup(groupName: string): LogGroupConfig | undefined {
    return this.groups[groupName];
  }

  getAllGroups(): Record<string, LogGroupConfig> {
    return { ...this.groups };
  }

  enableAll() {
    Object.values(this.groups).forEach((group) => (group.active = true));
  }

  disableAll() {
    Object.values(this.groups).forEach((group) => (group.active = false));
  }

  enableGroups(names: string[]) {
    this.disableAll();
    names.forEach((name) => {
      if (this.groups[name]) {
        this.groups[name].active = true;
      }
    });
  }

  disableGroups(names: string[]) {
    names.forEach((name) => {
      if (this.groups[name]) {
        this.groups[name].active = false;
      }
    });
  }
}
